package cn.mapway.ib.client.widget;

import cn.mapway.ib.client.ClientContext;
import cn.mapway.ib.client.rpc.AppInstallProxy;
import cn.mapway.ib.share.model.common.ApiResult;
import cn.mapway.ib.share.model.dir.DirFile;
import cn.mapway.ui.client.mvc.Size;
import cn.mapway.ui.client.util.StringUtil;
import cn.mapway.ui.client.widget.CommonEventComposite;
import cn.mapway.ui.client.widget.dialog.Dialog;
import cn.mapway.ui.client.widget.dialog.SaveBar;
import cn.mapway.ui.shared.CommonEvent;
import com.google.gwt.core.client.Callback;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import jsinterop.base.Js;

import java.util.Date;
import java.util.List;

public class DirSelector extends CommonEventComposite {
    private static final DirSelectorUiBinder ourUiBinder = GWT.create(DirSelectorUiBinder.class);
    public static Dialog<DirSelector> dialog;
    @UiField
    DirTree tree;
    @UiField
    HorizontalPanel bar;
    @UiField
    SaveBar saveBar;
    @UiField
    FlexTable filesTable;
    String selectedPath;

    public DirSelector() {
        initWidget(ourUiBinder.createAndBindUi(this));
        saveBar.enableSave(false);
        tree.addSelectionHandler(item -> {
            TreeItem selectedItem = item.getSelectedItem();
            DirFile dirFile = Js.uncheckedCast(selectedItem.getUserObject());
            selectedPath = dirFile.location;
            saveBar.message(selectedPath);
            saveBar.enableSave(true);

            tree.loadSubFolder(selectedItem, false);

            loadFiles(selectedPath);
            renderBar(selectedPath);
        });
    }

    public static Dialog<DirSelector> getDialog(boolean reuse) {
        if (reuse) {
            if (dialog == null) {
                dialog = createOne();
            }
            return dialog;
        } else {
            return createOne();
        }
    }

    private static Dialog<DirSelector> createOne() {
        DirSelector selector = new DirSelector();
        return new Dialog<>(selector, "目录选择");
    }

    private void renderBar(String selectedPath) {
        bar.clear();
        List<String> segs = StringUtil.splitIgnoreBlank(selectedPath, "/");
        String absPath = "";
        for (String s : segs) {
            absPath += "/" + s;
            Anchor anchor = new Anchor(s);
            anchor.setTitle(absPath);
            anchor.addClickHandler((event) -> {
                tree.loadPath(anchor.getTitle());
            });
            bar.add(anchor);
            bar.add(new Label("/"));
        }
    }

    private void loadFiles(String selectedPath) {
        AppInstallProxy.listfiles(selectedPath, new Callback<ApiResult<DirFile[]>, String>() {
            @Override
            public void onFailure(String reason) {
                ClientContext.alert(reason);
            }

            @Override
            public void onSuccess(ApiResult<DirFile[]> result) {
                if (result.isSuccess()) {
                    filesTable.removeAllRows();
                    DirFile[] data = result.data;
                    int row = 0;
                    int col = 0;
                    FlexTable.FlexCellFormatter cellFormatter = filesTable.getFlexCellFormatter();
                    for (int i = 0; i < data.length; i++) {
                        col = 0;
                        DirFile dirFile = data[i];
                        filesTable.setText(row, col++, StringUtil.extractName(dirFile.location));
                        filesTable.setText(row, col, StringUtil.formatFileSize(dirFile.size));
                        cellFormatter.setHorizontalAlignment(row, col++, HasHorizontalAlignment.ALIGN_RIGHT);
                        filesTable.setText(row, col++, StringUtil.formatDate(new Date(dirFile.lastModifyTime)));
                        row++;
                    }
                    HTMLTable.ColumnFormatter columnFormatter = filesTable.getColumnFormatter();
                    if (data.length > 0) {
                        columnFormatter.setWidth(1, "90px");
                        columnFormatter.setWidth(2, "160px");
                    }

                } else {
                    ClientContext.alert(result.message);
                }
            }
        });
    }

    @Override
    public Size requireDefaultSize() {
        int width = Window.getClientWidth() - 400;
        int height = Window.getClientHeight() - 300;
        return new Size(width, height);
    }

    @UiHandler("saveBar")
    public void saveBarCommon(CommonEvent event) {
        if (event.isOk()) {
            fireEvent(CommonEvent.okEvent(selectedPath));
        } else {
            fireEvent(event);
        }
    }

    interface DirSelectorUiBinder extends UiBinder<DockLayoutPanel, DirSelector> {
    }
}